package leetcode;

import java.util.*;

public class Lc692 {


    public List<String> topKFrequent(String[] words, int k) {

        HashMap<String, WordCount> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            WordCount wordCount = map.getOrDefault(words[i], new WordCount(words[i], 0));
            wordCount.count ++;
            map.put(words[i], wordCount);

        }
        PriorityQueue<WordCount> pq = new PriorityQueue<>();
        for (Map.Entry<String, WordCount> en : map.entrySet()) {
            pq.offer(en.getValue());
        }
        ArrayList<String> ans = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            ans.add(pq.poll().word);
        }

        return ans;
    }

//    public static void main(String[] args) {
//        Lc692 lc692 = new Lc692();
//        lc692.topKFrequent(new String[]{"i", "love", "leetcode", "i", "love", "coding"}, 2);
//    }

}

class WordCount implements Comparable {
    public String word;
    public int count;
    public WordCount(String word, int count) {
        this.count = count;
        this.word = word;
    }


    @Override
    public int compareTo(Object o) {
        WordCount other = (WordCount) o;
        if (this.count == other.count) {
            return this.word.compareTo(other.word);
        }
        return other.count - this.count;
    }
}